package utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Encapsulates the data to track each iteration of the SOM training
 */
public class ExecData {

	/**
	 * Holds the data for the iteration- quantization and topological errors
	 */
	public class IterData {
		
		public double quantError; // quantization error of iteration
		public double topologicalError; // topological error of iteration
		
		/**
		 * Constructor- creates a new pair holding data for
		 * the iteration
		 * @param quantError quantization error of iteration
		 * @param topologicalError topological error of iteration
		 */
		public IterData(double quantError, double topologicalError) {
			super();
			this.quantError = quantError;
			this.topologicalError = topologicalError;
		}
	}
	
	/* 
	 * holds data for all iterations of training the SOM
	 */
	private List<IterData> executionData;

	/**
	 * Constructor- creates a new object to hold the return value
	 * of the SOM training
	 */
	public ExecData() {
		super();
		executionData = new LinkedList<IterData>();
	}
	
	/**
	 * Adds quantization and topological errors for a new iteration
	 * @param quantError quantization error of iteration
	 * @param topologicalError topological error of iteration
	 */
	public void addIterData(double quantError, double topologicalError) {
		executionData.add(new IterData(quantError, topologicalError));
	}

	/**
	 * Returns quantization error of indicated iteration
	 * @param iterNum number of wanted iteration
	 * @return quantization error of indicated iteration
	 */
	public double getQuantError(int iterNum) {
		return executionData.get(iterNum).quantError;
	}
	
	/**
	 * Returns topological error of indicated iteration
	 * @param iterNum number of wanted iteration
	 * @return topological error of indicated iteration
	 */
	public double getTopologicalError(int iterNum) {
		return executionData.get(iterNum).topologicalError;
	}
	
	/**
	 * Creates a CSV file for the execution data
	 * @param fileName name for the generated CSV file
	 */
	public void createsCsvFiles(String fileName)
	{
		FileWriter writer = null;
		try {
			writer = new FileWriter(new File(fileName+".csv"));
			
			writer.write(",Quantization Error, Topological Error\n");
			double prevFit = -1, prevAva = -1;
			int i = 0;
			for(IterData data : executionData)
			{
				if(data.quantError != prevFit || data.topologicalError != prevAva)
				{					
					writer.write(i+","+data.quantError+","+data.topologicalError+"\n");
					prevAva = data.topologicalError; prevFit = data.quantError;
				}
				i++;
			}
			writer.close();
		} catch (IOException e) {		
			e.printStackTrace();
		}
	}
}